import { constantRoutes, dynamicRoutes } from '@/router/modules/routeRecordRaw'
import router from '@/router'
import { AuthState } from '@/stores/interface'
import MenuAPI from '@/api/module/system/menu'
import { RouteRecordRaw } from 'vue-router'
import { pinia } from '../index'
const modules = import.meta.glob('../../views/**/**.vue')
const Layout = () => import('@/layouts/index.vue')

export const useAuthStore = defineStore('eco-auth', {
  state: (): AuthState => ({
    // 路由
    authRoutes: [],
    // 左侧菜单
    authLeftMenus: [],
    // 菜单
    authMenus: []
  }),
  getters: {
    getAuthRoutes: state => state.authRoutes,
    getAuthLeftMenus: state => state.authLeftMenus
  },
  actions: {
    setAuthRoutes() {
      return new Promise<RouteRecordRaw[]>((resolve, reject) => {
        // 后端获取动态路由
        MenuAPI.getRouters()
          .then(({ data }) => {
            // 转换路由
            const routes = conversionRouter(data)
            // 固定路由
            dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route))
            this.authRoutes = constantRoutes.concat(routes)
            resolve(routes)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    /**
     * 设置左侧菜单
     *
     * @param topMenuPath 顶层菜单路径
     */
    setAuthLeftMenus(topMenuPath: string) {
      const matchedItem = this.authRoutes.find(item => item.path === topMenuPath)
      if (matchedItem && matchedItem.children) {
        this.authLeftMenus = matchedItem.children
      }
    }
  }
})

const conversionRouter = (routes: RouteRecordRaw[]) => {
  const asyncRoutes: RouteRecordRaw[] = []
  routes.forEach(route => {
    const tmpRoute = { ...route } as RouteRecordRaw
    if (tmpRoute.component?.toString() === 'ParentView') {
      delete tmpRoute.component
    }
    // 顶级 目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == 'Layout') {
      tmpRoute.component = Layout
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`]
      if (component) {
        tmpRoute.component = component
      } else {
        tmpRoute.component = modules[`../../views/error/404.vue`]
      }
    }

    // 递归子菜单
    if (tmpRoute.children) {
      tmpRoute.children = conversionRouter(route.children as RouteRecordRaw[])
    }
    asyncRoutes.push(tmpRoute)
  })
  return asyncRoutes
}

export const useAuthStoreWithOut = () => {
  return useAuthStore(pinia)
}
